package uutalk.netcloud.talk.app.ui.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.theartofdev.edmodo.cropper.CropImage;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.android.BaseActivity;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.Md5Utils;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoadListener;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoader;
import uutalk.netcloud.talk.base.util.thirdpart.QiNiuManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.base.util.view.ViewUtil;
import uutalk.netcloud.talk.base.widget.CenterWindowTips;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.DBEntityManager;
import uutalk.netcloud.talk.model.bean.LoginInfo;
import uutalk.netcloud.talk.model.bean.MqttBussinessBean;
import uutalk.netcloud.talk.model.bean.SimpleEventType;
import uutalk.netcloud.talk.model.bean.UserInfo;

/**
 * Created by pmt
 */

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.name)
    TextView name;

    @BindView(R.id.per_name)
    EditText perName;

    @BindView(R.id.sex)
    TextView sex;

    @BindView(R.id.email)
    EditText email;

    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.password)
    EditText password;

    @BindView(R.id.person_icon)
    RoundedImageView headIV;

    @BindView(R.id.password_layout)
    View password_layout;

    String uploadHeadUrl = null;


    boolean isEidt = false;

    @Override
    public int layoutId() {
        return R.layout.activity_person_detail;
    }

    @Override
    public void init() {
        setUserInfo();
        addRightMenu();
    }

    private void addRightMenu() {
        TextView view = (TextView) LayoutInflater.from(mActivity).inflate(R.layout.menu_text, null);
        view.setText(LanguageUtil.getStringById(R.string.edit));
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEidt) {
                    view.setText(LanguageUtil.getStringById(R.string.finish));
                    isEidt = true;
                    perName.requestFocus();
                    password.setEnabled(true);
                    perName.setEnabled(true);
                    email.setEnabled(true);
                    phone.setEnabled(true);
                } else {
                    view.setText(LanguageUtil.getStringById(R.string.edit));
                    isEidt = false;
                    if (check()) {
                        if (MQTTManager.getInstance().isConnected()) {
                            requestSetUserInfo();
                        } else {
                            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.get_data_erro));
                        }
                    }
                }
            }
        });
        addCustomMenu(view);
    }

    @Override
    public boolean autoBindEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvenet(MqttMessageEvent event) throws JSONException {
        if (CMDConstant.SET_USER_INFO_RESP_CMD.equals(event.getMessage().getCmd())) {

            progressHudUtil.dismissProgressHud();
            MqttBussinessBean bussinessBean = JSON.parseObject(event.getMessage().toString(), MqttBussinessBean.class);
            if (bussinessBean.isOk()) {
                String userId = new JSONObject(event.getMessage().toString()).getString("user_id");
                UserInfo userInfo = new UserInfo();
                userInfo.setEmail(ViewUtil.getText(true, email));
                userInfo.setName(ViewUtil.getText(true, perName));
                userInfo.setPhone(ViewUtil.getText(true, phone));
                userInfo.setUser_id(userId);
                userInfo.setPicture(uploadHeadUrl == null ? UserManager.getInstance().getUserInfo().getPicture() : uploadHeadUrl);


                UserManager.getInstance().saveUserInfoToLocal(userInfo);
                LoginInfo loginInfo = UserManager.getInstance().getLoginInfo();

                loginInfo.setDevicePassword(ViewUtil.getText(true, password));
                UserManager.getInstance().saveLoginInfoToLocal(loginInfo);

                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.edit_succ));
                DBEntityManager.saveUserInfo(userInfo);
                EventMamager.getInstance().postEvent(SimpleEventType.USER_INFO_CHANGE);

                finish();
            } else {
                ToastUtil.makeToast(bussinessBean.getError_msg());
            }
        }
    }


    private void requestSetUserInfo() {
        progressHudUtil.showProgressHud();
        UserInfo userInfo = UserManager.getInstance().getUserInfo();

        String headUrl = uploadHeadUrl == null ? UserManager.getInstance().getUserInfo().getPicture() : uploadHeadUrl;
        String passwordaa = ViewUtil.isEmpty(password) ? null : Md5Utils.md5(ViewUtil.getText(true, password));

        Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createSetUserInfoBean(UserManager.getInstance().getLoginInfo().getDeviceId(), userInfo.getUser_id(), ViewUtil.getText(true, perName), headUrl, ViewUtil.getText(true, email), ViewUtil.getText(true, phone), passwordaa));
        MQTTManager.getInstance().publish(publication);
    }

    private boolean check() {
        if (ViewUtil.isEmpty(perName)) {
            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.edit_name));
            return false;
        }
        return true;
    }


    private void setUserInfo() {
        UserInfo userInfo = UserManager.getInstance().getUserInfo();
        ImageLoader.loadImageBitmap(mActivity, QiNiuManager.QINIU_HOST + userInfo.getPicture(), new ImageLoadListener() {
            @Override
            public void onLoadComplete(Object t) {
                headIV.setImageBitmap((Bitmap)t);
            }

            @Override
            public void onLoadFail() {

            }
        });
        name.setText(userInfo.getName());
        perName.setText(userInfo.getName());
        email.setText(userInfo.getEmail());
        phone.setText(userInfo.getPhone());

        LoginInfo loginInfo = UserManager.getInstance().getLoginInfo();
        password.setText(loginInfo.getDevicePassword());

        //游客不能编辑用户信息
        if (UserManager.getInstance().getLoginInfo().getUserType().equals("2")) {
            password_layout.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.person_icon)
    public void onHeadClick() {
        if (isEidt) {
            PictureSelector.create(this).openGallery(PictureMimeType.ofImage()).selectionMode(PictureConfig.SINGLE).forResult(PictureConfig.CHOOSE_REQUEST);
        }
    }

//    @OnClick(R.id.logout_activity)
//    public void onLogout(){
//        CenterWindowTips alertView = new CenterWindowTips(mActivity);
//        alertView.setContentStr("是否退出当前账号？");
//        alertView.setContentGravity(Gravity.CENTER);
//        alertView.setsureButtonStr("确定");
//        alertView.setType(CenterWindowTips.TYPE_DOUBLE);
//        alertView.setClickListener(new CenterWindowTips.OnClickListener() {
//            @Override
//            public void onSureClick() {
//                if(NetUtil.isNetworkAvailable(mActivity)){
//                    Intent intent = new Intent(mActivity, LoginActivity.class);
//                    intent.putExtra("exit", true);
//                    startActivity(intent);
//                }else {
//                    ToastUtil.makeToast("请检查网络连接");
//                }
//
//            }
//
//            @Override
//            public void onCancelClick() {
//
//            }
//
//        });
//        alertView.show();
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (data != null) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    CropImage.activity(Uri.fromFile(new File(selectList.get(0).getPath()))).setAspectRatio(1, 1).setFixAspectRatio(true).start(this, CropActivity.class);
                    overridePendingTransition(0, 0);
                }
            }
        }


        //裁剪回调
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                uploadHead(resultUri.getPath());
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                ToastUtil.makeToast("图片裁剪出错,请重试");
            } else if (resultCode == RESULT_CANCELED) {

            }
        }


    }

    private void uploadHead(String filePath) {
        progressHudUtil.showProgressHud();

        QiNiuManager.getInstance().uploadImage(new File(filePath), new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                progressHudUtil.dismissProgressHud();
                if (info != null && info.isOK()) {
                    uploadHeadUrl = key;
                    ImageLoader.loadImage(mActivity, filePath, headIV);
                } else {
                    ToastUtil.makeToast("头像设置失败");
                    uploadHeadUrl = null;
                }
            }
        });
    }


}
